package com.pomr.service.common.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.pomr.entity.bigscr.PersonBind;
import com.pomr.model.equipmentstorage.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.pomr.dao.base.BaseDao;
import com.pomr.model.data.EquipmentMessage;
import com.pomr.model.data.MonitorMessage;
import com.pomr.service.common.EquipmentMessageService;
@Service
public class EquipmentMessageServiceImpl implements EquipmentMessageService {
	@Autowired
	@Qualifier("baseDaoImpl")
	private BaseDao baseDao;
	
	@Override
	public EquipmentMessage searchEquipBySn(String sn) throws Exception {
		// 先查询领用表，如果没有领用，直接查询设备信息表
		EquipmentMessage e = null;
		String hql = "from Receive r left join fetch r.match where (r.receiveTime =null or r.receiveTime='') and r.match.equipmentdetail.sN = '"+sn+"'";
		List<Receive> list = baseDao.findByHql(hql);
		if(list==null || list.size()<=0){
			hql = "from EquipmentStorageDetail e where e.sN = '"+sn+"'";
			List<EquipmentStorageDetail> details = baseDao.findByHql(hql);
			if(details!=null && details.size()>0){
				e = new EquipmentMessage(details.get(0), null);
			}
		}else{
			Receive r = list.get(0);
			e = new EquipmentMessage(r.getMatch().getEquipmentdetail(), r.getMatch().getSimdetail());
			//获取设备绑定人
			List<EquipmentLeader> equipmentLeaders = baseDao.findByHql("from EquipmentLeader where receive.id="+r.getId()+" and (nouseTime=null or nouseTime='')");
			if(equipmentLeaders!=null && !equipmentLeaders.isEmpty()){
				List<PersonBind> personBinds = new ArrayList<>();
				for(EquipmentLeader leader:equipmentLeaders){
					PersonBind personBind = new PersonBind();
					personBind.setName(leader.getRecord().getName());
					personBind.setIdcard(leader.getRecord().getIdcard());
					personBind.setUserNo(leader.getUserNo());
					personBinds.add(personBind);
				}
				e.addbinds(personBinds);
			}
		}

		return e;
	}

	@Override
	public List<MonitorMessage> searchMonitorBySn(String sn, String startTime, String endTime, String idcard) throws Exception {
		String hql = "from MonitoringData m where m.leader.receive.match.equipmentdetail.sN = '"+sn+"' and m.leader.record.idcard='"+idcard+"'";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Date> map = new HashMap<String, Date>();
		int i = -1;
		if(startTime!=null && !startTime.equals("")){
			hql += " and m.monitorTime>=:starttime";
			map.put("starttime", sdf.parse(startTime));
			i = 1;
		}
		if(endTime!=null && !endTime.equals("")){
			hql += " and m.monitorTime<=:endtime";
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(sdf.parse(endTime));
	        calendar.add(Calendar.DAY_OF_YEAR, 1);
	        map.put("endtime", calendar.getTime());
	        i = 1;
		}
		if(i < 0){//没有设置查看时间 默认当前一个月
			hql += " and m.monitorTime>=:starttime";
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
	        calendar.add(Calendar.MONTH, -1);
	        map.put("starttime", calendar.getTime());
		}
		hql += " order by m.monitorTime desc";
		List<MonitoringData> list = baseDao.findByHqlNoCacheWithDate(hql, map);
		List<MonitorMessage> monitors = new ArrayList<MonitorMessage>();
		if(list!=null && list.size()>0){
			for(int k=0; k<list.size(); k++){
				monitors.add(new MonitorMessage(list.get(k)));
			}
		}
		return monitors;
	}
	
	/**
	 * 验证字符串时候为日期
	 * @param strDate
	 * @return
	 */
	private boolean isDate(String strDate) {
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

	@Override
	public List<EquipmentMessage> searchEquipByIdcard(String idcard) throws Exception {
		//查询用户绑定的未退还的设备
//		String hql = "from DeviceMatch where id in (select r.match.id from Receive r where (r.receiveTime =null or r.receiveTime='') and r.record.idcard='"+idcard+"')";
		String hql = "from DeviceMatch where id in (select el.receive.match.id from EquipmentLeader el " +
				"where el.record.idcard='"+idcard+"' and (el.receive.receiveTime =null or el.receive.receiveTime='')" +
				" and (el.nouseTime =null or el.nouseTime=''))";

		List<DeviceMatch> list = baseDao.findByHql(hql);
		List<EquipmentMessage> ems = new ArrayList<EquipmentMessage>();
		if(list!=null && list.size()>0){
			for(int i=0; i<list.size(); i++){
				DeviceMatch r = list.get(i);
				ems.add(new EquipmentMessage(r.getEquipmentdetail(), r.getSimdetail()));
			}
		}
		return ems;
	}

}
